package com.itggm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itggm.Result.ResponseResult;
import com.itggm.dto.DeptPageDTO;
import com.itggm.exception.BusinessException;
import com.itggm.mapper.UserMapper;
import com.itggm.pojo.Dept;
import com.itggm.pojo.User;
import com.itggm.service.DeptService;
import com.itggm.mapper.DeptMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
* @author root
* @description 针对表【sys_dept】的数据库操作Service实现
* @createDate 2024-12-21 11:46:42
*/
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService{
    @Resource
    private DeptMapper deptMapper;
    @Resource
    private UserMapper userMapper;

    @Override
    public ResponseResult deptPage(DeptPageDTO deptPageDTO) {
        //获取分页对象
        Integer page = deptPageDTO.getPage();
        Integer limit = deptPageDTO.getLimit();
        String deptName = deptPageDTO.getDeptName();
        Page<Dept> deptPage = new Page<>(page,limit);
        //构建分页条件
        LambdaQueryWrapper<Dept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(ObjectUtils.isNotEmpty(deptName),Dept::getDeptName,deptName).orderByDesc(Dept::getCreateTime);
        //执行分页
        baseMapper.selectPage(deptPage,queryWrapper);
        //封装返回结果
        return ResponseResult.success()
                .data("total",deptPage.getTotal())
                .data("tableData",deptPage.getRecords());
    }

    @Override
    public void delete(Integer id) {
        //根据部门id查询用户表
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getDeptId,id);
        List<User> users = userMapper.selectList(userWrapper);
        //判断该部门下是否有员工
        if (users.size()>0){
            throw new BusinessException("该部门下有员工，无法删除");
        }
        deptMapper.deleteById(id);

    }
}




